$(function() {
    renderCard("con_five", function(data) {
        console.log(data);
    });

});

//日期拆分
function captureTime(date) {
	var timeArr = date.replace(" ", ":").replace(/\:/g, "-").split("-");
	var nian = timeArr[0];
	var yue = timeArr[1];
	var ri = timeArr[2];
	var shi = timeArr[3];
	var fen = timeArr[4];
	var miao = timeArr[5];
	var str = nian + '-' + yue + '-' + ri
	return str;
}

function renderCard(id, linkCallback) {
    var card = $("#" + id);
    var url = card.attr('url');
    var body = card.find('.card-body');

    var ul = body.find(">ul");
    // 加载中，停止处理scroll事件
    if (ul.data('loading')) {
        return;
    }
    ul.empty();

    body.scroll(function() {

        var height = $(this).height();
        var scrollHeight = ul.height();
        if (scrollHeight <= height) {
            return;
        }
        var nScrollTop = $(this)[0].scrollTop;
        // console.log(scrollHeight, height, nScrollTop)
        if (scrollHeight - height <= nScrollTop) {
            ul.data('loading', true);
            // 滚动到底部
            setTimeout(function() {
                fetchDataAndAppend(url, ul, linkCallback);
            }, 500);
        }
    });
    
    fetchDataAndAppend(url, ul, linkCallback);
}

function fetchDataAndAppend(url, ul, linkCallback) {
    var loadMask = ul.closest('.card').find('.dealMask');
    
    loadMask.show();
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json'
    }).done(function(res) {

        res.rows.forEach(function(row) {
            var line = $('<li>', {
                'className': 'card-body-line'
            });
            var link = $('<a>');
            link.data('data', row);
            link.click(function() {
                linkCallback($(this).closest('a').data('data'));
            });
            var titleSpan = $('<span>', {
                html: row.transactTitle
            });
            link.append(titleSpan);
            var date = captureTime(row.createTime);
            var dateSpan = $('<span>', {
                html: date.substring(5, 10)
            });
            dateSpan.css('float', 'right');
            dateSpan.css('color', '#b3b0b0');
            link.append(dateSpan);
            line.append(link);
            ul.append(line);
        });
        ul.data('loading', false);
        loadMask.hide();
    }).fail(function() {
        ul.data('loading', false);
        loadMask.hide();
    });
}